package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.common.MyTouch;
import com.loveto.constant.LovetoConstant;
import com.loveto.model.MessageBoxInfo;

public class MessageMainActivity extends BaseActivity implements
View.OnClickListener, View.OnTouchListener {

	// 사용하는 변수들
	private Intent intentMoveToPage;
	private LinearLayout contentMainList; // 전체 레이아웃 // LinearLayout
	private LinearLayout friendMessageList;
	private ProgressDialog progressDialog; // 프로그레스다이얼로그
	private String gender = "";
	private String memberid = "";
	private int newMessageCnt;
	private int not_select_winner_tournamentID;
	private int not_view_winner_tournamentID;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_message_main);
		
		// 터치 리스너 달기 // 버튼
		RelativeLayout footer01 = (RelativeLayout) findViewById(R.id.btn_footer01);
		footer01.setOnTouchListener(this);
		RelativeLayout footer02 = (RelativeLayout) findViewById(R.id.btn_footer02);
		footer02.setOnTouchListener(this);
		RelativeLayout footer04 = (RelativeLayout) findViewById(R.id.btn_footer04);
		footer04.setOnTouchListener(this);
		RelativeLayout footer05 = (RelativeLayout) findViewById(R.id.btn_footer05);
		footer05.setOnTouchListener(this);
		
		RelativeLayout friendListCntbar = (RelativeLayout)findViewById(R.id.friend_list_cnt_bar);
		friendListCntbar.setOnClickListener(this);
		
		// 초기화
		contentMainList = (LinearLayout)findViewById(R.id.content_main_list);
		friendMessageList = (LinearLayout)findViewById(R.id.friend_list_message_list);
		progressDialog = new ProgressDialog(MessageMainActivity.this);
		
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		gender = pref.getString("gender", "");
		
		
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		newMessageCnt = 0;
		friendMessageList.removeAllViews();
		new SetMessageBoxListTask().execute();
	}
	
	@Override
	public void onClick(View v) {
		RelativeLayout vParent;
		TextView messagememberseqTextView;
		String messagememberseq;
		Intent intent;
		
		switch (v.getId()) {
		case R.id.friend_photo:
			vParent = (RelativeLayout)v.getParent();
			TextView v_userID = (TextView)vParent.findViewById(R.id.userID);
			String userID = (String)v_userID.getText();
			intent = new Intent(MessageMainActivity.this, UserinfoViewOthersActivity.class);
			intent.putExtra("memberid_other", userID);
			startActivity(intent);
			break;
		case R.id.last_message_text:
			vParent = (RelativeLayout)v.getParent();
			vParent = (RelativeLayout)vParent.getParent();
			messagememberseqTextView = (TextView)vParent.findViewById(R.id.messagememberseq);
			messagememberseq = (String)messagememberseqTextView.getText();
			gotoMessageFriendActivity(vParent, messagememberseq);
			break;
		case R.id.message_arrow:
			vParent = (RelativeLayout)v.getParent();
			messagememberseqTextView = (TextView)vParent.findViewById(R.id.messagememberseq);
			messagememberseq = (String)messagememberseqTextView.getText();
			gotoMessageFriendActivity(vParent, messagememberseq);
			break;
		case R.id.friend_list_cnt_bar:
			intent = new Intent(MessageMainActivity.this, FriendsListActivity.class);
			startActivity(intent);
			break;
		case R.id.last_system_message:
			intent = new Intent(MessageMainActivity.this, MessageNoticeActivity.class);
			startActivity(intent);
			break;
		}
	}

	private void gotoMessageFriendActivity(RelativeLayout vParent,
			String messagememberseq) {
		TextView friendInfoTextView;
		String friendInfo;
		intentMoveToPage = new Intent(MessageMainActivity.this,
				MessageFriendActivity.class);
		intentMoveToPage.putExtra("messageMemberSeq", messagememberseq);
		friendInfoTextView = (TextView)vParent.findViewById(R.id.friend_userinfo_text);
		friendInfo = (String)friendInfoTextView.getText();
		intentMoveToPage.putExtra("friendInfo", friendInfo);
		startActivity(intentMoveToPage);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_footer01:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(LovotoMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer02:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(JoinedTournamentListActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer03:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(MessageMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer04:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(UserinfoViewMineActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer05:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(SetupMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		}
		return true;
	}

	//화면 전환 시켜주기
	private void gotoActive(Class class1,View v,int d) {
		intentMoveToPage = new Intent(MessageMainActivity.this,
				class1);
		startActivity(intentMoveToPage);
		v.setBackgroundResource(d);
	}
	
// background 작업에 사용할 data의 자료형: Void 형
	// background 작업 진행 표시를 위해 사용할 인자: RelativeLayout
	// background 작업의 결과를 표현할 자료형: String[]
	public class SetMessageBoxListTask extends AsyncTask<String, Object, List<String>>{
		private List<RelativeLayout> messageBoxInfoLayoutList; // 하나의 row Layout 들을 간직한 List
		
		// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
		// 작업 시작을 UI에 표현하거나
		// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
		@Override
		protected void onPreExecute() {
			progressDialog.setMessage("리스트를 불러오고 있습니다.");
			progressDialog.show();
			
			// 하나의 row Layout 들을 간직한 List 초기화
			messageBoxInfoLayoutList = new ArrayList<RelativeLayout>();
			// 전체 레이아웃 초기화
			//contentMainList.removeAllViews();

			Log.d("tag", "Background 작업 시작 ");
			super.onPreExecute();
		}

		// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback
		@Override
		protected List<String> doInBackground(String... params) {
			// TODO Auto-generated method stub
			// 토너먼트 리스트 만들기
			List<String> photoUrlList = new ArrayList<String>(); // 사진url array
			
			Log.d("tag", "json 가져오기 ");
			try {
				StringBuffer url = new StringBuffer(LovetoConstant.MESSAGE_BOX_LIST_URL);
				url.append("?memberid=").append(memberid).append("&gender=").append(gender);
				Log.d("tag", "url : " + url);
				String jsonText = JsonUtils.getStringFromUrl(url.toString());
				Log.d("tag", jsonText);
				// 원격에서 읽어온 데이터로 JSON 객체 생성
				try {
					if (jsonText == null) {
						AsyncTask: cancel(true);
					}
					
					JSONObject jsonObject = new JSONObject(jsonText);
					//JSONArray jsonArray = new JSONArray(jsonText);
					Log.d("tag", "" + jsonObject);
					Log.d("tag", "" + jsonObject.getString("friend_num"));
					String friendNum = jsonObject.getString("friend_num");
					Log.d("tag", "" + friendNum);
					publishProgress(friendNum);
					not_select_winner_tournamentID = jsonObject.getInt("not_select_winner_tournamentID");
					Log.d("tag", "not_select_winner_tournamentID: " + not_select_winner_tournamentID);
					not_view_winner_tournamentID = jsonObject.getInt("not_view_winner_tournamentID");
					Log.d("tag", "not_view_winner_tournamentID: " + not_view_winner_tournamentID);
					
					JSONObject systemMsgInfoObj = jsonObject.getJSONObject("system_msg_info");
					Log.d("tag", "" + systemMsgInfoObj);
					String dataYn = systemMsgInfoObj.getString("data_yn");
					Log.d("tag", "dataYn : " + dataYn);
					if (!"N".equals(dataYn)) {
						newMessageCnt = newMessageCnt + systemMsgInfoObj.getInt("new_cnt");
					}
					
					publishProgress(systemMsgInfoObj);
					
					//String listJsonString = jsonArray.getJSONObject(1).getString("list");
					JSONArray messageBoxJSONArray = jsonObject.getJSONArray("list");
					//JSONArray messageBoxJSONArray = new JSONArray(listJsonString);
					Log.d("tag", messageBoxJSONArray.toString());
					int jsonArrayLen = messageBoxJSONArray.length();
					Log.d("tag", "jsonArrayLen = " + jsonArrayLen);
					// JSONObject object = new Json(jsonText);
					// Log.d("tag", jsonArray.toString());
					// Log.d("tag", "" + jsonArray.length()); 

					// 사진을 전체 다운로드를 위하여 // 초기화
					photoUrlList =  new ArrayList<String>(jsonArrayLen); 

					for (int i = 0; i < jsonArrayLen; i++) {
						JSONObject object = messageBoxJSONArray.getJSONObject(i);
						// Log.d("tag", "" + object.toString());
						MessageBoxInfo messageBoxInfo = new MessageBoxInfo(object.getInt("messagemember_seq"), object.getString("sender_memberid"),
								object.getString("receiver_memberid"), object.getString("messagecontent"), object.getString("read_yn"),
								object.getString("regdate"), object.getString("sender_local"), object.getString("sender_local_detail"), object.getString("sender_age"),
								object.getString("sender_gender"), object.getString("receiver_local"), object.getString("receiver_local_detail"),
								object.getString("receiver_age"), object.getString("receiver_gender"), object.get("new_cnt")==null?0:object.getInt("new_cnt"));

						// 하나의 row 만들기
						RelativeLayout messageBoxInfoLayout = makeRelativeLayout(messageBoxInfo, photoUrlList);
						// 기능 : 메인 layout 에 add // 콜백함수 : onProgressUpdate
						publishProgress(messageBoxInfoLayout);
						// 사진 전체 다운로드를 위하여
						messageBoxInfoLayoutList.add(messageBoxInfoLayout);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				Log.d("tag", "겟 제이슨 실패!");
				AsyncTask: cancel(true); //Json 값 가져오기 실패 시 Async 진행 중단 및 onCancel 호출.
			}

			return photoUrlList;
		}

		// onInBackground(...)에서 publishProgress(...)를 사용하면
		// 자동 호출되는 callback으로
		// 이곳에서 ProgressBar를 증가 시키고, text 정보를 update하는 등의
		// background 작업 진행 상황을 UI에 표현함.
		// (예제에서는 UI스레드의 ProgressBar를 update 함)
		@Override
		protected void onProgressUpdate(Object... progress) {
			if (progress[0] instanceof String) {
				TextView friendNum = (TextView)contentMainList.findViewById(R.id.friend_num);
				friendNum.setText("쪽지 친구 " + (String)progress[0] + "명");
			} else if (progress[0] instanceof RelativeLayout) {
				friendMessageList.addView((RelativeLayout)progress[0]);
			} else if (progress[0] instanceof JSONObject) {
				final JSONObject systemMsgInfoObj = (JSONObject)progress[0];
				updateLastSystemMessageLayout(systemMsgInfoObj);
			}
		}

		// onInBackground(...)가 완료되면 자동으로 실행되는 callback
		// 이곳에서 onInBackground가 리턴한 정보를 UI위젯에 표시 하는 등의 작업을 수행함.
		// (예제에서는 작업에 걸린 총 시간을 UI위젯 중 TextView에 표시함)
		@Override
		protected void onPostExecute(List<String> photoUrlList) {
			// 사진 한꺼번에 다운로드
			ImageDownloader imageDownloader = new ImageDownloader();
			int photoUrlArraySize = photoUrlList.size();
			for (int i = 0; i < photoUrlArraySize; i++) {
				String photoUrl = photoUrlList.get(i);
				ImageView imgView = (ImageView)messageBoxInfoLayoutList.get(i).findViewById(R.id.friend_photo);
				imageDownloader.download(photoUrl, imgView);
			}
			
			//풋터에 새로 받은 쪽지 개수 띄워주기
			Log.d("tag", "newMessageCnt: " + newMessageCnt);
			TextView vNewMsg = (TextView)findViewById(R.id.message_new_cnt);
			if (newMessageCnt!=0) {
				vNewMsg.setText("" + newMessageCnt);
				vNewMsg.setVisibility(TextView.VISIBLE);
			} else {
				vNewMsg.setVisibility(TextView.GONE);
			}
			//승자선택 안한 주최 토너먼트 or 결과확인 안 한 참여 토너먼트 팝업
			if (not_select_winner_tournamentID != 0 || not_view_winner_tournamentID != 0) {
				showSimpleAlertForSelectOrViewWinner();
			}
			// 프로그레스 다이얼로그 끄기
			progressDialog.dismiss();
			
			// 아무것도 없을 경우
			if(photoUrlArraySize == 0) {
				viewToast(Gravity.CENTER, 0, 0, "데이터가 없습니다.");
			}
			
			Log.d("tag", "화면 노출 ");
		}

		// AsyncTask.cancel(boolean) 메소드가 true 인자로
		// 실행되면 호출되는 콜백.
		// background 작업이 취소될때 꼭 해야될 작업은 여기에 구현.
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			progressDialog.dismiss();
		}
	}

	// 하나의 row를 만들기
	private RelativeLayout makeRelativeLayout(MessageBoxInfo messageBoxInfo, List<String> photoUrlList) {
		RelativeLayout messageBoxInfoLayout = null;
		if ("M".equals(gender)) { // 쪽지 대상은 여자(Female)
			messageBoxInfoLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_box_woman, null);
		} else {
			messageBoxInfoLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_box_man, null);
		}
		
		String friendMemberid = "";
		String friendLocal = "";
		String friendLocalDetail = "";
		String friendAge = "";
		String readyn = messageBoxInfo.getReadYn();
		
		if (memberid.equals(messageBoxInfo.getSenderMemberid())) {
			friendMemberid = messageBoxInfo.getReceiverMemberid();
			friendLocal = messageBoxInfo.getReceiverLocal();
			friendLocalDetail = messageBoxInfo.getReceiverLocalDetail();
			friendAge = messageBoxInfo.getReceiverAge();
		} else {
			friendMemberid = messageBoxInfo.getSenderMemberid();
			friendLocal = messageBoxInfo.getSenderLocal();
			friendLocalDetail = messageBoxInfo.getSenderLocalDetail();
			friendAge = messageBoxInfo.getSenderAge();
			//새로 받은 쪽지 개수 더하기
			newMessageCnt = newMessageCnt + messageBoxInfo.getNewCnt();
		}
		
		// 메시지 아이콘 설정
		ImageView messageType = (ImageView)messageBoxInfoLayout.findViewById(R.id.message_type);
		
		if (memberid.equals(messageBoxInfo.getSenderMemberid())) {
			// sent message
			// layout 의 디폴트 이미지가 sent message 이미지이므로 변경 x
		} else if (readyn.equals("N")) {
			// new message
			messageType.setImageResource(R.drawable.icon_message_new);
			TextView extraText1 = (TextView)messageBoxInfoLayout.findViewById(R.id.extra_text1);
			TextView extraText2 = (TextView)messageBoxInfoLayout.findViewById(R.id.extra_text2);
			extraText1.setText(messageBoxInfo.getNewCnt() + "");
			extraText2.setText(messageBoxInfo.getNewCnt() + "");
		} else {
			// received message
			messageType.setImageResource(R.drawable.icon_message_received);
		}
		

		// 유저 인포 텍스트 변경
		StringBuffer sb = new StringBuffer();
		sb.append(friendMemberid);
		sb.append(", ");
		sb.append(friendLocal);
		if (friendLocalDetail != null) {
			if ( (!friendLocalDetail.equals("")) && (!friendLocalDetail.equals("null"))) {
				sb.append(" ");
				sb.append(friendLocalDetail);
			}
		}
		sb.append(", ");
		sb.append(friendAge);
		TextView userInfo = (TextView)messageBoxInfoLayout.findViewById(R.id.friend_userinfo_text);
		userInfo.setText(sb);

		// 쪽지친구 seq 달아주기
		TextView messagememberSeq = (TextView)messageBoxInfoLayout.findViewById(R.id.messagememberseq);
		messagememberSeq.setText("" + messageBoxInfo.getMessagememberSeq());
		
		// 쪽지친구 멤버아이디 달아주기
		TextView userIDTextView = (TextView)messageBoxInfoLayout.findViewById(R.id.userID);
		userIDTextView.setText(friendMemberid);

		// 마지막 쪽지 메시지
		TextView lastMessageText = (TextView)messageBoxInfoLayout.findViewById(R.id.last_message_text);
		lastMessageText.setText(messageBoxInfo.getMessageContent());
		
		// 마감 시간
		TextView lastMessageTime = (TextView)messageBoxInfoLayout.findViewById(R.id.last_message_time);
		lastMessageTime.setText(messageBoxInfo.getRegdate());

		// 사진 셋팅
		// StringBuffer 초기화
		sb.setLength(0);
		// 재사용
		sb.append(LovetoConstant.PHOTO_THUMB_URL);
		sb.append(friendMemberid);
		sb.append(".jpg");
		photoUrlList.add(sb.toString());

		//클릭 리스너 달기
		ImageView userphoto = (ImageView)messageBoxInfoLayout.findViewById(R.id.friend_photo);
		userphoto.setOnClickListener(this); //사진
		userInfo.setOnClickListener(this); //유저정보텍스트
		TextView messageTextLayout = (TextView)messageBoxInfoLayout.findViewById(R.id.last_message_text);
		messageTextLayout.setOnClickListener(this); //말풍선
		ImageView userarrow = (ImageView)messageBoxInfoLayout.findViewById(R.id.message_arrow);
		userarrow.setOnClickListener(this);

		return messageBoxInfoLayout;
	}

	public void updateLastSystemMessageLayout(JSONObject systemMsgInfoObj) {
		Log.d("tag", "" + systemMsgInfoObj);
		String dataYn;
		try {
			dataYn = systemMsgInfoObj.getString("data_yn");
			Log.d("tag", "dataYn : " + dataYn);
			RelativeLayout relativeLayout = (RelativeLayout)contentMainList.findViewById(R.id.last_system_message);
			
			if ("Y".equals(dataYn)) {
				TextView newMsgTextView = (TextView)relativeLayout.findViewById(R.id.new_system_message);
				newMsgTextView.setText("! 시스템 공지 - 안 읽은 메시지(" + systemMsgInfoObj.getInt("new_cnt") + ")");
				
				TextView newMsgRegdateTextView = (TextView)relativeLayout.findViewById(R.id.new_system_message_regdate);
				newMsgRegdateTextView.setText(systemMsgInfoObj.getString("regdate"));
				
				String tournamentMakerMemberid = systemMsgInfoObj.getString("tournament_maker_memberid");
				String messageType = systemMsgInfoObj.getString("message_type");
				String message = "[" + tournamentMakerMemberid + "] " + LovetoConstant.systemMessageMap.get(messageType);
				TextView msgCotentTextView = (TextView)relativeLayout.findViewById(R.id.new_system_message_content);
				msgCotentTextView.setText(message);
				Log.d("tag", "message : " + message);
				
				relativeLayout.setOnClickListener(this);
				
			} else {
				contentMainList.removeView(relativeLayout);
			}
			
		} catch (JSONException e) {
			Log.e("tag", "시스템 쪽지 세팅 중 오류 발생" + e.getMessage());
			viewToast("시스템 쪽지 세팅 중 오류 발생");
		}
	}
	
	private void showSimpleAlertForSelectOrViewWinner() {
		String title;
		String msg;
		if (not_select_winner_tournamentID != 0) {
			title = "토너먼트 주최완료!";
			msg = "주최 한 토너먼트의 마감시간이 완료되어 우승자를 결정해야합니다. 이동하시겠습니까?";
		} else {
			title = "우승자 결정완료!";
			msg = "참여 한 토너먼트의 우승자 결정이 완료되었습니다. 결과를 보기위해 이동하시겠습니까?";
		}
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(msg)
		.setPositiveButton("이동", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				if (isNetworkAvailableAndNotice()) {
					dialog.dismiss();
					int gotoTournamentID = 0;
					if (not_select_winner_tournamentID != 0) {
						gotoTournamentID = not_select_winner_tournamentID;
					} else {
						gotoTournamentID = not_view_winner_tournamentID;
					}
					Intent intent = new Intent(MessageMainActivity.this, InfoTournamentActivity.class);
					intent.putExtra("tournamentID", "" + gotoTournamentID);
					startActivity(intent);
					
				} else {
					dialog.dismiss();
				}
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		}).show();
		
	}
}
